package 多线程.控制多线程的顺序执行;

import org.junit.Test;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * create at 2018/11/1
 * author: suveng
 * email: suveng@163.com
 **/
public class App {
    private static Thread thread1 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("thread1");
        }
    });
    private static Thread thread2 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("thread2");
        }
    });
    private static Thread thread3 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("thread3");
        }
    });
     private static ExecutorService executorService=Executors.newSingleThreadExecutor();

    @Test
    public void joinTest() throws InterruptedException {
//        通过join() 方法保证线程的顺序，但是这样子就和单线程没什么区别了。
//        join()是让主线程等待子线程结束后 继续运行
        thread1.start();
        thread1.join();

        thread2.start();
        thread2.join();

        thread3.start();
        thread3.join();
    }

    /**
     * 通过singleThreadPool来控制线程顺序，singleThreadPool是FIFO先进先出的一个线程池
     */
    @Test
    public void executorTest(){
        executorService.submit(thread1);
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println("i am second");
            }
        });
        executorService.submit(() -> System.out.println("i am third"));
        executorService.submit(thread2);
        executorService.submit(thread3);
    }
}
